package com.zhonghui.wms.controller;

import com.zhonghui.common.annotation.Log;
import com.zhonghui.common.core.controller.BaseController;
import com.zhonghui.common.core.page.TableDataInfo;
import com.zhonghui.common.enums.BusinessType;
import com.zhonghui.common.utils.DateUtils;
import com.zhonghui.common.utils.SecurityUtils;
import com.zhonghui.common.utils.StringUtils;
import com.zhonghui.common.utils.poi.ExcelUtil;
import com.zhonghui.response.BaseResult;
import com.zhonghui.wms.domain.WmsOutboundApplication;
import com.zhonghui.wms.domain.WmsOutboundApplicationDetails;
import com.zhonghui.wms.domain.vo.WmsInventoryDetailsVo;
import com.zhonghui.wms.domain.vo.WmsOutboundApplicationVo;
import com.zhonghui.wms.service.IWmsInventoryDetailsService;
import com.zhonghui.wms.service.IWmsOutboundApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 智能仓储WMS-出库申请Controller
 *
 * @author zhonghui
 * @date 2023-08-08
 */
@Api(tags="智能仓储WMS-出库申请")
@RestController
@RequestMapping("/wms/outboundApplication")
public class WmsOutboundApplicationController extends BaseController
{
    @Autowired
    private IWmsOutboundApplicationService wmsOutboundApplicationService;

    @Autowired
    private IWmsInventoryDetailsService wmsInventoryDetailsService;

    /**
     * 查询智能仓储WMS-出库申请列表
     */
    @ApiOperation("查询智能仓储WMS-出库申请列表")
    @GetMapping("/list")
    public TableDataInfo<List<WmsOutboundApplicationVo>> list(WmsOutboundApplicationVo wmsOutboundApplicationVo)
    {
        startPage();
        List<WmsOutboundApplicationVo> list = wmsOutboundApplicationService.selectWmsOutboundApplicationList(wmsOutboundApplicationVo);
        return getDataTable(list);
    }

    /**
     * 导出智能仓储WMS-出库申请列表
     */
    @ApiOperation("导出智能仓储WMS-出库申请列表")
    @Log(title = "智能仓储WMS-出库申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsOutboundApplicationVo wmsOutboundApplicationVo)
    {
        List<WmsOutboundApplicationVo> list = wmsOutboundApplicationService.selectWmsOutboundApplicationList(wmsOutboundApplicationVo);
        ExcelUtil<WmsOutboundApplicationVo> util = new ExcelUtil<WmsOutboundApplicationVo>(WmsOutboundApplicationVo.class);
        util.exportExcel(response, list, "智能仓储WMS-出库申请数据");
    }

    /**
     * 获取智能仓储WMS-出库申请详细信息
     */
    @ApiOperation("获取智能仓储WMS-出库申请详细信息")
    @GetMapping(value = "/{id}")
    public BaseResult<WmsOutboundApplicationVo> getInfo(@PathVariable("id") Long id)
    {
        return BaseResult.success(wmsOutboundApplicationService.selectWmsOutboundApplicationById(id));
    }

    /**
     * 新增智能仓储WMS-出库申请
     */
    @ApiOperation("新增智能仓储WMS-出库申请")
    @Log(title = "智能仓储WMS-出库申请", businessType = BusinessType.INSERT)
    @PostMapping
    public BaseResult<Integer> add(@RequestBody WmsOutboundApplicationVo wmsOutboundApplicationVo)
    {
        // 申请状态 0未提交 1待审核 2已审核
        wmsOutboundApplicationVo.setApplicationStatus(Long.parseLong("0"));
        return BaseResult.success(wmsOutboundApplicationService.insertWmsOutboundApplication(wmsOutboundApplicationVo));
    }

    /**
     * 修改智能仓储WMS-出库申请
     */
    @ApiOperation("修改智能仓储WMS-出库申请")
    @Log(title = "智能仓储WMS-出库申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public BaseResult<Integer> edit(@RequestBody WmsOutboundApplicationVo wmsOutboundApplicationVo)
    {
        wmsOutboundApplicationVo.setApplicationStatus(Long.parseLong("0"));
        wmsOutboundApplicationVo.setApproved(null);
        wmsOutboundApplicationVo.setApprovedStatus(null);
        wmsOutboundApplicationVo.setApprovedDate(null);
        wmsOutboundApplicationVo.setApprovedComments("");
        return BaseResult.success(wmsOutboundApplicationService.updateWmsOutboundApplication(wmsOutboundApplicationVo));
    }

    /**
     * 提交智能仓储WMS-出库申请
     */
    @ApiOperation("提交智能仓储WMS-出库申请")
    @Log(title = "出库申请", businessType = BusinessType.UPDATE)
    @PutMapping("/submit")
    public BaseResult<Integer> submit(@RequestBody WmsOutboundApplicationVo wmsOutboundApplicationVo) {
        // 检查库存是否充足
        List<WmsOutboundApplicationDetails> applyList = wmsOutboundApplicationVo.getWmsOutboundApplicationDetailsList();
        final StringBuilder msg = new StringBuilder();
        // 遍历出库明细
        applyList.stream().forEach(item->{
            // 构建物料库存明细查询条件
            WmsInventoryDetailsVo wiDetailsVo = new WmsInventoryDetailsVo();
            wiDetailsVo.setWarehouseId(item.getWarehouseId());
            wiDetailsVo.setWarehouseAreaId(item.getWarehouseAreaId());
            wiDetailsVo.setWarehouseSeatId(item.getWarehouseSeatId());
            wiDetailsVo.setMaterialId(item.getMaterialId());
            wiDetailsVo.setBatchNumber(item.getBatchNumber());
            List<WmsInventoryDetailsVo> inventoryDetailsVoList = wmsInventoryDetailsService.selectWmsInventoryDetailsList(wiDetailsVo);
            // 查询集合为空，则代表物料库存不存在该物料
            if(inventoryDetailsVoList == null || inventoryDetailsVoList.isEmpty()) {
                msg.append("库存中不存在当前物料："+item.getMaterialName()+"，出库失败！！！");
            }else {
                WmsInventoryDetailsVo material = inventoryDetailsVoList.get(0);
                double total = material.getExistingInventory() == null ? 0:material.getExistingInventory();
                double lock = material.getLockInventory()==null?0:material.getLockInventory();
                double inventory = total - lock;
                // 获取出库明细中的出库数量
                double outInventory = item.getOutboundNumber() ==null ? 0 : item.getOutboundNumber();
                // 判断出库数量是否大于物料库存
                if(inventory < outInventory) {
                    msg.append("当前库存："+inventory+"，小于出库数量："+outInventory+";库存不足不能出库");
                }
            }
        });
        if(StringUtils.isNotBlank(msg.toString())) {
            return BaseResult.error(msg.toString());
        }
        wmsOutboundApplicationVo.setApplicationStatus(Long.parseLong("1"));
        wmsOutboundApplicationVo.setApplicationDate(DateUtils.getNowDate());
        if(wmsOutboundApplicationVo.getId() != null) {
            // 修改提交
            WmsOutboundApplicationVo applicationVo = wmsOutboundApplicationService.selectWmsOutboundApplicationById(wmsOutboundApplicationVo.getId());
            if(applicationVo == null) {
                return BaseResult.error("此入库申请不存在，不能提交！");
            }
            wmsOutboundApplicationVo.setApproved(null);
            wmsOutboundApplicationVo.setApprovedStatus(null);
            wmsOutboundApplicationVo.setApprovedDate(null);
            wmsOutboundApplicationVo.setApprovedComments("");
            return BaseResult.success(wmsOutboundApplicationService.updateWmsOutboundApplication(wmsOutboundApplicationVo));
        }else {
            // 申请状态 0未提交 1待审核 2已审核
            wmsOutboundApplicationVo.setApplicationStatus(Long.parseLong("1"));
            // 新增提交
            return BaseResult.success(wmsOutboundApplicationService.insertWmsOutboundApplication(wmsOutboundApplicationVo));
        }
    }

    /**
     * 审核智能仓储WMS-出库申请
     */
    @ApiOperation("审核智能仓储WMS-出库申请")
    @Log(title = "出库申请", businessType = BusinessType.UPDATE)
    @PutMapping("/approve")
    public BaseResult<Integer> approve(@RequestBody WmsOutboundApplicationVo wmsOutboundApplicationVo) {
        wmsOutboundApplicationVo.setApplicationStatus(Long.parseLong("2"));
        wmsOutboundApplicationVo.setApprovedDate(DateUtils.getNowDate());
        wmsOutboundApplicationVo.setApproved(SecurityUtils.getUserId());
        return BaseResult.success(wmsOutboundApplicationService.updateWmsOutboundApplication(wmsOutboundApplicationVo));
    }
    /**
     * 删除智能仓储WMS-出库申请
     */
    @ApiOperation("删除智能仓储WMS-出库申请")
    @Log(title = "智能仓储WMS-出库申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public BaseResult<Integer> remove(@PathVariable Long[] ids)
    {
        return BaseResult.success(wmsOutboundApplicationService.deleteWmsOutboundApplicationByIds(ids));
    }

    @ApiOperation("智能仓储WMS-出库申请-执行拣货")
    @Log(title = "智能仓储WMS-出库申请-执行拣货", businessType = BusinessType.UPDATE)
    @PostMapping("/outBound")
    public BaseResult<Integer> outBound(@RequestBody WmsOutboundApplication wmsOutboundApplication)
    {
        wmsOutboundApplicationService.executeOutbound(wmsOutboundApplication.getId());
        return BaseResult.success();
    }

    @ApiOperation("智能仓储WMS-出库申请-出库盘点")
    @Log(title = "智能仓储WMS-出库申请-出库盘点", businessType = BusinessType.UPDATE)
    @PostMapping("/outInventoryInfo")
    public BaseResult<Integer> outInventoryInfo(@RequestBody WmsOutboundApplication wmsOutboundApplication)
    {
        WmsOutboundApplicationVo applicationVo = wmsOutboundApplicationService.selectWmsOutboundApplicationById(wmsOutboundApplication.getId());
        //设置状态
        applicationVo.setDocumentStatus(Long.parseLong("2"));
        return BaseResult.success(wmsOutboundApplicationService.updateWmsOutboundApplication(applicationVo));
    }

    @ApiOperation("智能仓储WMS-出库申请-发货")
    @Log(title = "智能仓储WMS-出库申请-发货", businessType = BusinessType.UPDATE)
    @PostMapping("/delivery")
    public BaseResult<Integer> delivery(@RequestBody WmsOutboundApplication wmsOutboundApplication)
    {
        wmsOutboundApplicationService.executeDelivery(wmsOutboundApplication.getId());
        return BaseResult.success();
    }
}
